package com.simple.util;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @desc
 * @Author Simple
 * @Date 2025/7/3 21:46
 **/
@Component
public class RedisTemplateUtil {

    @Resource
    public StringRedisTemplate stringRedisTemplate;

    public boolean lock(String key, String clientId, int lockExpireInSecond) {
        // setIfAbsent 对应 Redis 的 SETNX 命令
        return Boolean.TRUE.equals(stringRedisTemplate.opsForValue()
                .setIfAbsent(key, clientId, lockExpireInSecond, TimeUnit.SECONDS));
    }

    public boolean unlock(String key, String clientId) {
        boolean result = Boolean.FALSE;
        if (clientId.equalsIgnoreCase(stringRedisTemplate.opsForValue().get(key))) {
            result = Boolean.TRUE.equals(stringRedisTemplate.delete(key));
        }
        return result;
    }
}
